import { defineStore } from 'pinia'
import { removeToken } from '@/utils/auth/token'
import { toLogin } from '@/utils/auth/router'
import { usePermissionStore, useTabStore } from '@/store'
import { resetRouter } from '@/router'
import { userGetuserInfo } from '@/api/user'
import type { userGetuserInfoReturnModel } from '@/api/user'
import type { FileItemModel } from '@/api/file'

export const useUserStore = defineStore('user', {
  state() {
    return {
      userInfo: <userGetuserInfoReturnModel> {},
    }
  },
  getters: {
    userId(): number | null {
      return this.userInfo.id || null
    },
    name(): string {
      return this.userInfo.userName || ''
    },
    avatar(): FileItemModel[] {
      return this.userInfo.avatar || []
    },
    role(): Array<string> {
      return this.userInfo.role || []
    },
  },
  actions: {
    async getUserInfo() {
      try {
        const { code, data } = await userGetuserInfo()
        if (code === 0) {
          this.userInfo = data
          this.userInfo.role = ['admin']
          return Promise.resolve(data)
        }
        else {
          return Promise.reject(code)
        }
      }
      catch (error) {
        return Promise.reject(error)
      }
    },
    async logout() {
      const { resetTabs } = useTabStore()
      const { resetPermission } = usePermissionStore()
      removeToken()
      resetPermission()
      resetTabs()
      resetRouter()
      this.$reset()
      toLogin()
    },
    setUserInfo(userInfo = {}) {
      this.userInfo = { ...this.userInfo, ...userInfo }
    },
  },
})
